﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Errors;
using EffiProz.Core.Results;
using EffiProz.Core.RowIO;

namespace EffiProz.Core.Navigators
{
    public class RowSetNavigatorClient : RowSetNavigator
    {
        public static Object[][] emptyTable = new Object[0][];

        //
        int currentOffset;
        int baseBlockSize;

        //
        Object[][] table;

        //
        public RowSetNavigatorClient()
        {
            table = emptyTable;
        }

        public RowSetNavigatorClient(int blockSize)
        {
            table = new Object[blockSize][];
        }

        public RowSetNavigatorClient(RowSetNavigator source, int offset,
                                     int blockSize)
        {

            this.size = source.size;
            this.baseBlockSize = blockSize;
            this.currentOffset = offset;
            table = new Object[blockSize][];

            source.absolute(offset);

            for (int count = 0; count < blockSize; count++)
            {
                table[count] = source.getCurrent();

                source.next();
            }

            source.beforeFirst();
        }

        /**
         * For communication of small resuls such as BATCHEXECRESPONSE
         */
        public void setData(Object[][] table)
        {
            this.table = table;
            this.size = table.Length;
        }

        public void setData(int index, Object[] data)
        {
            table[index] = data;
        }

        public Object[] getData(int index)
        {
            return table[index];
        }

        /**
         * Returns the current row object. Type of object is implementation defined.
         */
        public override Object[] getCurrent()
        {

            if (currentPos < 0 || currentPos >= size)
            {
                return null;
            }

            if (currentPos == currentOffset + table.Length)
            {
                getBlock(currentOffset + table.Length);
            }

            return table[currentPos - currentOffset];
        }

        public override Row getCurrentRow()
        {
            throw Error.runtimeError(ErrorCode.U_S0500, "RowSetNavigatorClient");
        }

        public override void remove()
        {
            throw Error.runtimeError(ErrorCode.U_S0500, "RowSetNavigatorClient");
        }

        public override void add(Object data)
        {

            ensureCapacity();

            table[size] = (Object[])data;

            size++;
        }

        public override void clear()
        {
            setData(emptyTable);
            reset();
        }

        public override bool absolute(int position)
        {

            if (position < 1)
            {
                position += size;
            }

            if (position < 0)
            {
                beforeFirst();

                return false;
            }

            if (position > size)
            {
                afterLast();

                return false;
            }

            if (size == 0)
            {
                return false;
            }

            currentPos = position;

            return true;
        }

        public override void close()
        {

            if (session != null)
            {
                if (currentOffset == 0 && table.Length == size) { }
                else
                {
                    session.closeNavigator(id);
                }
            }
        }

        public override void readSimple(RowInputInterface _in,
                               ResultMetaData meta)
        {

            size = _in.readInt();

            if (table.Length < size)
            {
                table = new Object[size][];
            }

            for (int i = 0; i < size; i++)
            {
                table[i] = _in.readData(meta.columnTypes);
            }
        }

        public override void writeSimple(RowOutputInterface _out,
                                ResultMetaData meta)
        {

            _out.writeInt(size);

            for (int i = 0; i < size; i++)
            {
                Object[] data = table[i];

                _out.writeData(meta.getColumnCount(), meta.columnTypes, data, null,
                              null);
            }
        }

        public override void read(RowInputInterface _in,
                         ResultMetaData meta)
        {

            id = _in.readLong();
            size = _in.readInt();
            currentOffset = _in.readInt();
            baseBlockSize = _in.readInt();

            if (table.Length < baseBlockSize)
            {
                table = new Object[baseBlockSize][];
            }

            for (int i = 0; i < baseBlockSize; i++)
            {
                table[i] = _in.readData(meta.columnTypes);
            }
        }

        public override void write(RowOutputInterface _out,
                          ResultMetaData meta)
        {

            int limit = size - currentOffset;

            if (limit > table.Length)
            {
                limit = table.Length;
            }

            _out.writeLong(id);
            _out.writeInt(size);
            _out.writeInt(currentOffset);
            _out.writeInt(limit);

            for (int i = 0; i < limit; i++)
            {
                Object[] data = table[i];

                _out.writeData(meta.getColumnCount(), meta.columnTypes, data, null,
                              null);
            }
        }

        /**
         * baseBlockSize remains unchanged.
         */
        void getBlock(int offset)
        {

            try
            {
                RowSetNavigatorClient source = session.getRows(id, offset,
                    baseBlockSize);

                table = source.table;
                currentOffset = source.currentOffset;
            }
            catch (CoreException) { }
        }

        private void ensureCapacity()
        {

            if (size == table.Length)
            {
                int newSize = size == 0 ? 1
                                                : size * 2;
                Object[][] newTable = new Object[newSize][];

                Array.Copy(table, 0, newTable, 0, size);

                table = newTable;
            }
        }

    }
}
